<template>
  <Spin :spinning="spinning">
    <BasicTree
      title=""
      toolbar
      search
      :clickRowToExpand="false"
      :treeData="treeData"
      :selectedKeys="selectedKeys"
      @select="handleSelect"
      treeKey="code"
      :expandedKeys="expandedKeys"
    />
  </Spin>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import { Spin } from 'ant-design-vue';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getDepartment } from '/@/api/system/system';
  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree, Spin },

    emits: ['select', 'ok'],
    setup(_, { emit }) {
      const treeData = ref<TreeItem[]>([]);
      let spinning = ref(false);
      let selectedKeys = ref([]);
      let expandedKeys = ref(['root']);
      async function fetch() {
        treeData.value = (await getDepartment()) || [];
        treeData.value = setChildren(treeData.value);
      }

      function setChildren(node) {
        node.forEach((item) => {
          item.key = item.code;
          item.title = item.name;
          if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            item.isLeaf = false;
            setChildren(item.children);
          } else {
            item.isLeaf = true;
          }
        });
        return node;
      }

      function handleSelect(keys, node) {
        emit('select', keys[0], node);
      }

      onMounted(() => {
        fetch();
      });
      return {
        treeData,
        handleSelect,
        selectedKeys,
        spinning,
        expandedKeys,
      };
    },
  });
</script>
